import 'package:get/get.dart';
import 'package:rjpb/shared/utils/storage_util.dart';
import 'package:rjpb/page/home/profile/apis/logout_api.dart';

class ProfileController extends GetxController {
  var userName = ''.obs;
  var email = ''.obs;
  var phoneNumber = ''.obs;
  var sex = ''.obs;
  var avatar = ''.obs;
  var roleName = ''.obs;

  @override
  void onInit() {
    super.onInit();
    fetchUserInfo();
  }

  Future<void> fetchUserInfo() async {
    try {
      final userInfo = await LogoutApi.getUserInfo();
      if (userInfo != null && userInfo['code'] == 200) {
        final user = userInfo['user'];
        userName.value = user['userName'] ?? '';
        email.value = user['email'] ?? '';
        phoneNumber.value = user['phonenumber'] ?? '';
        sex.value = user['sex'] ?? '';
        avatar.value = user['avatar'] ?? '';
        roleName.value = user['roles'][0]['roleName'] ?? '';
      } else {
        print("获取用户信息失败, ${userInfo?['msg'] ?? '未知错误'}");
      }
    } catch (e) {
      print("获取用户信息失败: $e");
    }
  }

  Future<void> logout() async {
    try {
      final logoutState = await LogoutApi.logout();
      if (logoutState != null && logoutState['code'] == 200) {
        // 清除本地存储的用户信息
        await StorageUtil.removeToken();
        await StorageUtil.clear();
        // 跳转到登录页面
        Get.offAllNamed('/login');
      } else {
        print("退出失败,${logoutState?['msg']} ?? '退出登录失败'");
      }
    } catch (e) {
      print("退出失败,${e}");
    }
  }
}
